package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Spot;
import cn.wolfcode.wolf2w.query.SpotQuery;
import cn.wolfcode.wolf2w.repository.SpotRepository;
import cn.wolfcode.wolf2w.service.ISpotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class SpotServiceImpl implements ISpotService {


    @Autowired
    private MongoTemplate template;

    @Autowired
    private SpotRepository repository;

    @Override
    public void save(Spot spot) {
        spot.setId(null);
        repository.save(spot);
    }

    @Override
    public void update(Spot spot) {
        repository.save(spot);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Spot get(String id) {
        Spot spot =repository.findById(id).orElse(null);
        return spot;
    }

    @Override
    public List<Spot> list() {
        return repository.findAll();
    }

    @Override
    public Page<Spot> query(SpotQuery qo) {
        //查询对象
        Query query = new Query();
        long total = template.count(query, Spot.class);
        if(total == 0){
            return Page.empty();
        }
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<Spot> list = template.find(query, Spot.class);

        //3:封装page对象
        return new PageImpl<Spot>(list,pageable,total);
    }

    @Override
    public void saveOrUpdate(Spot spot) {
        if (!(StringUtils.hasLength(spot.getId()))){
            spot.setId(null);
            this.save(spot);
        }else {
            this.update(spot);

        }
    }

 /*   @Override
    public void changeHotValue(int hot, String id) {
        Spot spot = this.get(id);
        spot.setIshot(hot);
       this.update(spot);
    }

    @Override
    public List<Spot> queryHotSpot() {
        //状态是热门 通过序号排序
        return repository.findByIshotOrderBySequence(Spot.STATE_HOT);
    }*/






}
